package xuesm.proxy.dynamic.cglib;

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/**
 * @Author: xuesm
 * @Description: CGLib动态代理
 * @Date: Create in 13:11 2019/4/4
 */
public class CGLibAgent implements MethodInterceptor{


	public Object getInstance(Class<?> clazz) throws Exception{

		Enhancer enhancer = new Enhancer();
		// 要把哪个设置成为即将生成的新的类的父类
		enhancer.setSuperclass(clazz);
		enhancer.setCallback(this);

		return enhancer.create();
	}



	@Override
	public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {

		before();
		Object obj = methodProxy.invokeSuper(o, objects);
		after();
		return null;
	}

	private void after() {
		System.out.println("CGLib 代理完成");
	}

	private void before() {

		System.out.println("CGlib 代理前");
	}
}
